package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.ArchiveInfo;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.ViewForEventRegisterTask;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.EventType;
import com.sl.au.entity.Option;
import com.sl.au.entity.User;
import com.sl.au.service.ArchiveInfoService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.OptionService;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONObject;

@RestController
@RequestMapping("/ui/archive")
public class ArchiveInfoController extends BaseController {

	@Autowired
	private ArchiveInfoService archiveInfoService;
	@Autowired
	private EventRegisterService eventRegisterService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private EventTypeService eventTypeService;
	@Autowired
	private EventReportService eventReportService;

	@RequestMapping("/findReportByReportId/{reportId}")
	public MsgHelper findReportByReportId(@PathVariable("reportId")String reportId){
		EventReport report = eventReportService.getRepository().findOne(reportId);
		return MsgHelper.success().put("report", report);
	}
	@RequestMapping(value = "/initHistory", method = RequestMethod.GET)
	public MsgHelper initHistory() {

		User user = this.getMyAccount().getUser();

		List<EventReport> list = new ArrayList<EventReport>();

		list = eventReportService.getEventReportByUser(0, 20, user, "createTime", Sort.Direction.DESC);

		return MsgHelper.success().put("histories", list);
	}

	/**
	 * 当前register的归档信息
	 * 
	 * @param eventId
	 * @return
	 */
	@RequestMapping(value = "/findArchiveByRegisterId/{eventId}", method = RequestMethod.GET)
	public MsgHelper findArchiveByRegisterId(@PathVariable("eventId") String eventId) {
		ArchiveInfo archive = archiveInfoService.findArchiveByRegisterId(eventId).get(0);
		return MsgHelper.success().put("archive", archive);
	}

	/*
	 * @RequestMapping(value = "/backRegister/{eventId}", method =
	 * RequestMethod.GET) public MsgHelper backRegister(@PathVariable("eventId")
	 * String eventId) { String rejectMemo = request.getParameter("rejectMemo");
	 * eventRegisterService.rejectEventRegister(eventId, rejectMemo,
	 * getMyAccount().getUser()); return MsgHelper.success(); }
	 */

	/**
	 * 退回事件页面
	 * 
	 * @param eventId
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/backRegisterUI/{eventId}")
	public ModelAndView backRegisterUI(@PathVariable("eventId") String eventId, ModelAndView modelAndView) {
		modelAndView.addObject("registerId", eventId);
		User user = getMyAccount().getUser();
		modelAndView.addObject("user", user);
		modelAndView.setViewName("mobile/archive/backRegisterUI");
		return modelAndView;
	}

	/**
	 * 接收事件
	 * 
	 * @param eventId
	 *            内部事件的id
	 * @return
	 */
	@RequestMapping("/receptRegister/{eventId}")
	public MsgHelper receptRegister(@PathVariable("eventId") String eventId) {
		User user = getMyAccount().getUser();
		eventRegisterService.reveiveEventRegister(eventId, user);
		return MsgHelper.success();
	}

	@RequestMapping("/showDetailRegister/{eventId}")
	public MsgHelper showDetailRegister(@PathVariable("eventId") String eventId) {
		return MsgHelper.success().put("register", eventRegisterService.getRepository().findOne(eventId));
	}

	@RequestMapping("/checkState/{eventId}")
	public MsgHelper checkState(@PathVariable("eventId") String eventId) {
		EventRegister findOne = eventRegisterService.getRepository().findOne(eventId);
		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已完结").get(0);
		// 已经被归档 无法再次归档
		if (findOne.getRegisterEventState().getId().equals(option.getId())) {
			return MsgHelper.failed();
		} else {
			// 尚未归档
			return MsgHelper.success();
		}
	}

	/**
	 * 事件回退
	 * 
	 * @param eventId
	 * @return
	 */
	@RequestMapping(value = "/backRegister/{eventId}", method = RequestMethod.POST)
	public Map<String, Object> backRegister(@PathVariable("eventId") String eventId,
			MultipartHttpServletRequest requests) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		String rejectMemo = request.getParameter("rejectMemo");

		MultipartFile file = requests.getFile("file");
		String url = "";
		if (file != null && !file.isEmpty()) {
			// 注意路径的构建
			url = getUploadFilePath(this.fileUploadPath, "img/eventTask", file);

		}
		eventRegisterService.rejectEventRegister(eventId, rejectMemo, getMyAccount().getUser(), url);
		code = 1;
		map.put("code", code);
		return map;
	}

	/**
	 * 完结事件 事件归档
	 * 
	 * @param eventId
	 *            事件ID
	 * @param requests
	 *            文件上传
	 * @param archiveInfo
	 * @return
	 */
	@RequestMapping(value = "/archiveEvent/{eventId}", method = RequestMethod.POST)
	public Map<String, Object> archiveEvent(@PathVariable("eventId") String eventId,
			MultipartHttpServletRequest requests, ArchiveInfo archiveInfo) {
		MultipartFile file = requests.getFile("file");

		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;

		archiveInfo.setArcheveDate(new Date());
		archiveInfo.setArchiver(getMyAccount().getUser());
		archiveInfo.setDealer(getMyAccount().getUser());
		String url = "";
		if (file != null && !file.isEmpty()) {
			// 注意路径的构建
			url = getUploadFilePath(this.fileUploadPath, "img/archive", file);
			archiveInfo.setPhotourl(url);
		}
		EventRegister findOne = eventRegisterService.getRepository().findOne(eventId);
		// 如果每一个内部事件完结,将上报事件完结
		EventReport report = findOne.getRegisterEventToReportEvent();

		List<EventRegister> registers = new ArrayList<>();
		List<EventRegister> all = eventRegisterService.findByReportId(report.getId());
		for (EventRegister e : all) {
			// 同级内部事件
			if (!findOne.getId().equals(e.getId())) {
				registers.add(e);
			}
		}

		if (registers.size() > 0) {// 有同级的内部事件
			if (allEnded(registers)) {
				EventTask findOneTask = new EventTask();// 自身的内部事件日志
				EventTask reportTask = new EventTask();// 上报事件的日志信息
				archiveInfoService.saveMany(findOne, archiveInfo, findOneTask, reportTask, report);
			} else {
				EventTask findOneTask = new EventTask();// 自身的内部事件日志
				archiveInfoService.saveMany(findOne, findOneTask, archiveInfo);
			}

		} else {// 没有其他的内部事件
			EventTask findOneTask = new EventTask();// 自身的内部事件日志
			EventTask reportTask = new EventTask();// 上报事件的日志信息
			archiveInfoService.saveMany(findOne, archiveInfo, findOneTask, reportTask, report);
		}

		code = 1;
		map.put("code", code);
		return map;
	}

	
	/**
	 * 完结事件 事件归档
	 * 
	 * @param eventId
	 *            事件ID
	 * @param requests
	 *            文件上传
	 * @param archiveInfo
	 * @return
	 */
	@RequestMapping(value = "/archiveEventWithoutInputFile/{eventId}", method = RequestMethod.POST)
	public Map<String, Object> archiveEvent(@PathVariable("eventId") String eventId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		
		String url = "";
		JSONObject project = JSONObject.fromObject(request.getParameter("archiveInfo"));
		ArchiveInfo archiveInfo = (ArchiveInfo) JSONObject.toBean(project, ArchiveInfo.class);
		
		archiveInfo.setArcheveDate(new Date());
		archiveInfo.setArchiver(getMyAccount().getUser());
		archiveInfo.setDealer(getMyAccount().getUser());
		
//		String url = "";
//		if (file != null && !file.isEmpty()) {
//			// 注意路径的构建
//			url = getUploadFilePath(this.fileUploadPath, "img/archive", file);
//			archiveInfo.setPhotourl(url);
//		}
		
		// 前端图片压缩上传功能
		if (archiveInfo.getPhotourl() != null
				&& archiveInfo.getPhotourl().contains("data:image/png;base64")) {
			String[] imgl = archiveInfo.getPhotourl().split(",");
			archiveInfo.setPhotourl("");
			url = this.saveImgWithBase64(this.fileUploadPath, "img/archive", archiveInfo.getId() + ".png",
					imgl[imgl.length - 1]);
		}
		//-------------------
		archiveInfo.setPhotourl(url);
		EventRegister findOne = eventRegisterService.getRepository().findOne(eventId);
		// 如果每一个内部事件完结,将上报事件完结
		EventReport report = findOne.getRegisterEventToReportEvent();
		
		List<EventRegister> registers = new ArrayList<>();
		List<EventRegister> all = eventRegisterService.findByReportId(report.getId());
		for (EventRegister e : all) {
			// 同级内部事件
			if (!findOne.getId().equals(e.getId())) {
				registers.add(e);
			}
		}
		
		if (registers.size() > 0) {// 有同级的内部事件
			if (allEnded(registers)) {
				EventTask findOneTask = new EventTask();// 自身的内部事件日志
				EventTask reportTask = new EventTask();// 上报事件的日志信息
				archiveInfoService.saveMany(findOne, archiveInfo, findOneTask, reportTask, report);
			} else {
				EventTask findOneTask = new EventTask();// 自身的内部事件日志
				archiveInfoService.saveMany(findOne, findOneTask, archiveInfo);
			}
			
		} else {// 没有其他的内部事件
			EventTask findOneTask = new EventTask();// 自身的内部事件日志
			EventTask reportTask = new EventTask();// 上报事件的日志信息
			archiveInfoService.saveMany(findOne, archiveInfo, findOneTask, reportTask, report);
		}
		
		code = 1;
		map.put("code", code);
		return map;
	}

	private boolean allEnded(List<EventRegister> registers) {
		for (EventRegister e : registers) {
			if (!"已完结".equals(e.getRegisterEventState().getTitle())) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 查找事件
	 * 
	 * @param eventId
	 *            事件的ID
	 * @return
	 */
	@RequestMapping("/findEventRegByEvendId/{eventId}")
	public MsgHelper findEventRegByEvendId(@PathVariable("eventId") String eventId) {
		EventRegister findOne = eventRegisterService.getRepository().findOne(eventId);
		EventType parentType = eventTypeService.getRepository()
				.findOne(findOne.getRegisterEventType().getEventParent());
		String pType = "";
		if (parentType != null) {
			pType = parentType.getEventName();
		}
		return MsgHelper.success().put("event", findOne).put("parentType", pType);
	}

	@RequestMapping("/initWaitingEventReg")
	public MsgHelper initWaitingEventReg() {
		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已分配").get(0);
		List<EventRegister> waitingEventReg = eventRegisterService.getPageByStateAndGrid(0, 100, option.getId(),
				this.getMyAccount().getUser().getId(), "", "createTime", null);
		// List<EventRegister> waitingEventReg =
		// eventRegisterService.initPageByStateId(0, 10, option.getId());
		return MsgHelper.success().put("waitingEventReg", waitingEventReg);
	}

	/**
	 * 初始化已完结(归档完成)的事件
	 * 
	 * @return
	 */
	@RequestMapping("/initArchievedEventReg")
	public MsgHelper initArchievedEventReg() {
		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已完结").get(0);

		// List<EventRegister> archievedEventReg =
		// eventRegisterService.initPageByStateId(0, 100, option.getId());
		List<ViewForEventRegisterTask> archievedEventReg = eventRegisterService.getPageByTaskStateAndOperate(0, 100,
				option.getId(), this.getMyAccount().getUser().getId(), "", "eventTaskTime", null);
		return MsgHelper.success().put("archievedEventReg", archievedEventReg);
	}

	/**
	 * 初始化正在处理中的事件
	 * 
	 * @return
	 */
	@RequestMapping("/initUnArchievedEventReg")
	public MsgHelper initUnArchievedEventReg() {

		Option option = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中").get(0);
		// List<EventRegister> unArchievedEventReg =
		// eventRegisterService.getPageByStateAndUser(0, 100, option.getId(),
		// this.getMyAccount().getUser().getId(), "", "createTime", null);

		List<ViewForEventRegisterTask> unArchievedEventReg = eventRegisterService.getPageByTaskStateAndOperate(0, 100,
				option.getId(), this.getMyAccount().getUser().getId(), "", "eventTaskTime", null);
		return MsgHelper.success().put("unArchievedEventReg", unArchievedEventReg);
	}

	@RequestMapping(value = "/operateArchive/{id}", method = RequestMethod.DELETE)
	public MsgHelper deleteById(@PathVariable("id") String id) {
		archiveInfoService.deleteById(id);
		return MsgHelper.success();
	}

	/**
	 * 初始化事件信息列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "/initPage", method = RequestMethod.POST)
	public Map<String, Object> initPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
//		List<ArchiveInfo> infos = null;
//		Integer count = null;
//		if (StringUtils.hasText(key)) {
//			infos = archiveInfoService.getArchivePageByKey(start, length, key, null, null);
//		} else {
//			infos = archiveInfoService.getArchivePage(start, length, null, null, null);
//		}

		List<Map<String, Object>> infos = null;
		int count = 0;
		String roleId = this.getMyAccount().getRole().getId();
		infos = archiveInfoService.getArchivePageByKeyAndRole(start, length, roleId,key, "createTime", "DESC");
		
		count = archiveInfoService.getArchiveCountByRole(roleId, key);// gridinfoservice.getCount(key);

		map.put("data", infos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		String device = request.getParameter("device");
		String type = request.getParameter("type");

		// String identify = request.getParameter("identify");
		// 移动端
		if (this.DEVICE.equals(device)) {
			modelAndView.setViewName("mobile/archive/indexOnPhone");
			modelAndView.addObject("user", getMyAccount().getUser());
			modelAndView.addObject("type", type);
		} else {
			// pc端
			modelAndView = createLayoutView("archive/index");
		}
		return modelAndView;
	}
}
